import { useFormCallback } from '@hooks/useFormCallback'
import { useNewsCategoryCreateMutation, useNewsCategoryUpdateMutation } from '@services/news'
import { Link } from '@tanstack/react-router'
import { Breadcrumb, Button, Form, Input, InputNumber, Switch } from 'antd'
import { useEffect } from 'react'
import { FormCard } from './FormCard'

export function FormNewsCategory({ defaultData }) {
  const [form] = Form.useForm()

  const { mutate } = defaultData.id
    ? useNewsCategoryUpdateMutation()
    : useNewsCategoryCreateMutation()
  const { onFinish, onFailed } = useFormCallback(mutate, {
    handle: (values) => ({ ...values, ...(defaultData.id && { id: defaultData.id }) }),
  })

  useEffect(() => {
    form.setFieldsValue(defaultData)
  }, [defaultData])

  const card = {
    title: (
      <Breadcrumb
        items={[
          { title: '新闻中心' },
          { title: <Link to="..">新闻类型</Link> },
          { title: defaultData.id ? '编辑' : '新增' },
        ]}
      />
    ),
  }
  return (
    <FormCard card={card}>
      <Form
        key={defaultData.id}
        name="form-news-category"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        style={{ maxWidth: '100%' }}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFailed}
        autoComplete="off">
        <Form.Item
          label="新闻类型"
          name="name"
          rules={[{ required: true, message: '请输入新闻类型' }]}>
          <Input />
        </Form.Item>
        <Form.Item label="排　　序" name="orderby" width={'206px'}>
          <InputNumber className="w-[206px]!" min={0} />
        </Form.Item>
        <Form.Item label="是否隐藏" name="hide">
          <Switch checkedChildren="隐藏" unCheckedChildren="显示" />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            保 存
          </Button>
        </Form.Item>
      </Form>
    </FormCard>
  )
}
